import 'package:flutter/material.dart';
import 'package:flutter_4/SQLiteHelper.dart';
import 'package:flutter_4/model/UserInfo.dart';
import 'package:oktoast/oktoast.dart';

// RegisterPageUI 注册
class RegisterPageUI extends StatefulWidget {

  RegisterPageUI({Key key}) : super(key: key);

  @override
  _RegisterPageUIState createState() => _RegisterPageUIState();
}

class _RegisterPageUIState extends State<RegisterPageUI> {

  /// 用户名
  TextEditingController userAccountController = new TextEditingController();
  /// 密码
  TextEditingController passwordController = new TextEditingController();
  /// 密码确认
  TextEditingController confirmController = new TextEditingController();


  @override
  void initState() {
     _init();
     super.initState();
  }

  SQLiteHelper _sqLiteHelper = new SQLiteHelper();
  _init() async {
    await _sqLiteHelper.openSqlite();
    // await _sqLiteHelper.insert(new UserInfo(id: 1, userAccount: '刘德华', password: '123456'));
    // await _sqLiteHelper.insert(new UserInfo(id: 2, userAccount: '张学友', password: '123456'));

    List<UserInfo> userInfoList = await _sqLiteHelper.queryAll();
    print('数据库个人信息表：');
    if(userInfoList != null){
      for(int i=0; i< userInfoList.length; i++){
        print(userInfoList[i].toJson());
      }
    }
    await _sqLiteHelper.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0.4,
          title: Text("注册"),
        ),
        body: content()
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///====================api========================
  _register() async {

    String userAccount = userAccountController.text;
    String passWord = passwordController.text;
    String confirm = confirmController.text;

    if (userAccount.isEmpty ||
        userAccount.trim().length < 7) {
      showToast('账号长度需要大于7位');
    } else if (passWord.isEmpty ||
        passWord.length < 8 ||
        passWord.length > 15 ) {
      showToast('密码需要大于8位小于15位');
    } else if (passWord != confirm) {
      showToast('两次输入的密码不正确！');
    } else {
      /// 打开数据库
      await _sqLiteHelper.openSqlite();
      UserInfo userInfo = await _sqLiteHelper.getUserInfoByAccount(userAccount);
      List<UserInfo> userInfoList = await _sqLiteHelper.queryAll();
      if(userInfo != null){
        showToast('该昵称已被占用');
      } else {
        if(userInfoList == null){
          _sqLiteHelper.insert(new UserInfo(id: 1, userAccount: userAccount, password: passWord));
        }else {
          _sqLiteHelper.insert(new UserInfo(id: userInfoList.length + 1, userAccount: userAccount, password: passWord));
        }
        showToast('注册成功!');
        Navigator.of(context).pushNamed('/login');
      }
      _sqLiteHelper.close();
    }

  }

  ///===================Widget======================
  Widget content(){
    return Padding(
      padding: EdgeInsets.all(16),
      child: Center(
        child: Column(
          children: <Widget>[
            SizedBox(
              height: 20,
            ),
            Container(
              padding: EdgeInsets.only(bottom: 10),
              alignment: Alignment.centerLeft,
              child: Text(
                "注册用户",
                style: TextStyle(fontSize: 18),
              ),
            ),
            Container(
              padding: EdgeInsets.only(bottom: 20),
              alignment: Alignment.centerLeft,
              child: Text(
                "用户注册后可使用收藏文章等众多功能！",
                style: TextStyle(fontSize: 14, color: Colors.grey),
              ),
            ),
            TextField(
              controller: userAccountController,
              autofocus: true,
              decoration: InputDecoration(
                labelText: "用户名",
                hintText: "请输入用户名或邮箱",
                labelStyle: TextStyle(color: Colors.blue),
                prefixIcon: Icon(Icons.person),
              ),
              maxLines: 1,
            ),
            TextField(
              controller: passwordController,
              decoration: InputDecoration(
                  labelText: "密码",
                  labelStyle: TextStyle(color: Colors.blue),
                  hintText: "请输入密码",
                  prefixIcon: Icon(Icons.lock)),
              obscureText: true,
              maxLines: 1,
            ),
            TextField(
              controller: confirmController,
              decoration: InputDecoration(
                  labelText: "再次输入密码",
                  labelStyle: TextStyle(color: Colors.blue),
                  hintText: "请再次输入密码",
                  prefixIcon: Icon(Icons.lock)),
              obscureText: true,
              maxLines: 1,
            ),

            button(),

          ],
        ),
      ),
    );
  }

  /// 注册按钮
  Widget button(){
    return Padding(
      padding: const EdgeInsets.only(top: 28.0),
      child: Row(
        children: <Widget>[
          Expanded(
            child: RaisedButton(
              padding: EdgeInsets.all(16.0),
              elevation: 0.5,
              child: Text("注册"),
              color: Colors.blue,
              textColor: Colors.white,
              onPressed: () {
                _register();
              },
            ),
          ),
        ],
      ),
    );
  }


}

